﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Linq.Dynamic;
using System.Text;
using System.Threading.Tasks;
using Abp;
using Abp.Application.Services.Dto;
using Abp.Authorization;
using Abp.AutoMapper;
using Abp.Configuration;
using Abp.Domain.Repositories;
using Abp.Extensions;
using Abp.Linq.Extensions;
using LeadThing.AbpZeroTemplate.ProjectStatuss.Authorization;
using LeadThing.AbpZeroTemplate.ProjectStatuss.Dtos;
using LeadThing.AbpZeroTemplate.Dto;
using LeadThing.AbpZeroTemplate.Files;
using LeadThing.AbpZeroTemplate.Areas;

namespace LeadThing.AbpZeroTemplate.ProjectStatuss
{
    /// <summary>
    /// 年度拟实施稳评的项目情况服务实现
    /// </summary>
    [AbpAuthorize(ProjectStatusAppPermissions.ProjectStatus)]


    public class ProjectStatusAppService : AbpZeroTemplateAppServiceBase, IProjectStatusAppService
    {
        private readonly IRepository<ProjectStatus, long> _projectStatusRepository;
        private readonly IProjectStatusListExcelExporter _projectStatusListExcelExporter;
        private readonly IRepository<File, long> _fileRepository;
        private readonly IRepository<Area, long> _areaRepository;


        private readonly ProjectStatusManage _projectStatusManage;
        /// <summary>
        /// 构造方法
        /// </summary>
        public ProjectStatusAppService(IRepository<ProjectStatus, long> projectStatusRepository,
ProjectStatusManage projectStatusManage
      , IProjectStatusListExcelExporter projectStatusListExcelExporter, IRepository<File, long> fileRepository, IRepository<Area, long> areaRepository
  )
        {
            _projectStatusRepository = projectStatusRepository;
            _projectStatusManage = projectStatusManage;
            _projectStatusListExcelExporter = projectStatusListExcelExporter;
            _fileRepository = fileRepository;
            _areaRepository = areaRepository;
        }


        #region 实体的自定义扩展方法
        private IQueryable<ProjectStatus> _projectStatusRepositoryAsNoTrack => _projectStatusRepository.GetAll().AsNoTracking();


        #endregion


        #region 年度拟实施稳评的项目情况管理

        /// <summary>
        /// 根据查询条件获取年度拟实施稳评的项目情况分页列表
        /// </summary>
        public async Task<PagedResultDto<ProjectStatusListDto>> GetPagedProjectStatussAsync(GetProjectStatusInput input)
        {

            var query = _projectStatusRepositoryAsNoTrack;
            //TODO:根据传入的参数添加过滤条件
            if (!string.IsNullOrWhiteSpace(input.Filter))
                query = query.Where(p => p.SituationTitle.Contains(input.Filter));

            var projectStatusCount = await query.CountAsync();

            var projectStatuss = await query
            .OrderByDescending(p => p.Id)
            .PageBy(input)
            .ToListAsync();

            var areaList = _areaRepository.GetAll();
            var fileList = _fileRepository.GetAll();
            return new PagedResultDto<ProjectStatusListDto>(projectStatusCount,
                projectStatuss.Select(item =>
                {
                    var dto = item.MapTo<ProjectStatusListDto>();
                    var townModel = areaList.Where(p => p.Id == dto.TownID).Select(p => new { p.Title }).FirstOrDefault();
                    if (townModel != null)
                        dto.TownTitle = townModel.Title;

                    var areaModel = areaList.Where(p => p.Id == dto.AreaID).Select(p => new { p.Title }).FirstOrDefault();
                    if (areaModel != null)
                        dto.AreaTitle = areaModel.Title;

                    var villModel = areaList.Where(p => p.Id == dto.VillageID).Select(p => new { p.Title }).FirstOrDefault();
                    if (villModel != null)
                        dto.VillageTitle = villModel.Title;

                    var fileModel = fileList.Where(p => p.Id == dto.FileID).Select(p => new { p.Title }).FirstOrDefault();
                    if (fileModel != null)
                        dto.FileTitle = fileModel.Title;

                    return dto;
                }).ToList());
        }

        /// <summary>
        /// 通过Id获取年度拟实施稳评的项目情况信息进行编辑或修改 
        /// </summary>
        public async Task<GetProjectStatusForEditOutput> GetProjectStatusForEditAsync(NullableIdDto<long> input)
        {
            var output = new GetProjectStatusForEditOutput();

            ProjectStatusEditDto projectStatusEditDto;

            if (input.Id.HasValue)
            {
                var entity = await _projectStatusRepository.GetAsync(input.Id.Value);
                projectStatusEditDto = entity.MapTo<ProjectStatusEditDto>();
            }
            else
            {
                projectStatusEditDto = new ProjectStatusEditDto();
            }

            output.ProjectStatus = projectStatusEditDto;
            return output;
        }


        /// <summary>
        /// 通过指定id获取年度拟实施稳评的项目情况ListDto信息
        /// </summary>
        public async Task<ProjectStatusListDto> GetProjectStatusByIdAsync(EntityDto<long> input)
        {
            var entity = await _projectStatusRepository.GetAsync(input.Id);

            return entity.MapTo<ProjectStatusListDto>();
        }







        /// <summary>
        /// 新增或更改年度拟实施稳评的项目情况
        /// </summary>
        public async Task CreateOrUpdateProjectStatusAsync(CreateOrUpdateProjectStatusInput input)
        {
            if (input.ProjectStatusEditDto.Id.HasValue)
            {
                await UpdateProjectStatusAsync(input.ProjectStatusEditDto);
            }
            else
            {
                await CreateProjectStatusAsync(input.ProjectStatusEditDto);
            }
        }

        /// <summary>
        /// 新增年度拟实施稳评的项目情况
        /// </summary>
        [AbpAuthorize(ProjectStatusAppPermissions.ProjectStatus_CreateProjectStatus)]
        public virtual async Task<ProjectStatusEditDto> CreateProjectStatusAsync(ProjectStatusEditDto input)
        {
            //TODO:新增前的逻辑判断，是否允许新增

            var entity = input.MapTo<ProjectStatus>();

            entity = await _projectStatusRepository.InsertAsync(entity);
            return entity.MapTo<ProjectStatusEditDto>();
        }

        /// <summary>
        /// 编辑年度拟实施稳评的项目情况
        /// </summary>
        [AbpAuthorize(ProjectStatusAppPermissions.ProjectStatus_EditProjectStatus)]
        public virtual async Task UpdateProjectStatusAsync(ProjectStatusEditDto input)
        {
            //TODO:更新前的逻辑判断，是否允许更新

            var entity = await _projectStatusRepository.GetAsync(input.Id.Value);
            input.MapTo(entity);

            await _projectStatusRepository.UpdateAsync(entity);
        }

        /// <summary>
        /// 删除年度拟实施稳评的项目情况
        /// </summary>
        [AbpAuthorize(ProjectStatusAppPermissions.ProjectStatus_DeleteProjectStatus)]
        public async Task DeleteProjectStatusAsync(EntityDto<long> input)
        {
            //TODO:删除前的逻辑判断，是否允许删除
            var model = _projectStatusRepository.FirstOrDefault(input.Id);
            await _fileRepository.DeleteAsync(model.FileID);

            await _projectStatusRepository.DeleteAsync(input.Id);
        }

        /// <summary>
        /// 批量删除年度拟实施稳评的项目情况
        /// </summary>
        [AbpAuthorize(ProjectStatusAppPermissions.ProjectStatus_DeleteProjectStatus)]
        public async Task BatchDeleteProjectStatusAsync(List<long> input)
        {
            //TODO:批量删除前的逻辑判断，是否允许删除
            await _projectStatusRepository.DeleteAsync(s => input.Contains(s.Id));
        }

        #endregion

        #region 年度拟实施稳评的项目情况的Excel导出功能


        public async Task<FileDto> GetProjectStatusToExcel()
        {
            var entities = await _projectStatusRepository.GetAll().ToListAsync();

            var dtos = entities.MapTo<List<ProjectStatusListDto>>();

            var fileDto = _projectStatusListExcelExporter.ExportProjectStatusToFile(dtos);



            return fileDto;
        }


        #endregion

    }
}
